package org.hxzon.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Console {

    private final BufferedReader in;
    private final PrintStream out;
    private ConsoleListener consoleListener;
    private boolean running;
    private final Lock lock;

    public Console() {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintStream(System.out, true);
        lock = new ReentrantLock();
    }

    public String readLine() {
        try {
            lock.lock();
            String m = in.readLine();
            lock.unlock();
            return m;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void println(String m) {
        lock.lock();
        out.println(m);
        lock.unlock();
    }

    public void setConsoleListener(ConsoleListener listener) {
        this.consoleListener = listener;
    }

    public Thread startListen() {
        running = true;
        Thread t = new Thread() {
            public void run() {
                while (running && consoleListener != null) {
                    consoleListener.listen(readLine(), Console.this);
                }
            }
        };
        t.start();
        return t;
    }

    public void stopListen() {
        running = false;
    }

    public boolean isListen() {
        return running;
    }

    public interface ConsoleListener {
        public void listen(String m, Console console);
    }

    public static void test() {
        Console c = new Console();
        c.setConsoleListener(new ConsoleListener() {
            public void listen(String m, Console console) {
                if ("quit".equals(m)) {
                    console.stopListen();
                    return;
                }
                console.println(m);
                console.println("please more one line...");
                console.println(console.readLine());
                console.println("please input...");
            }
        });
        c.println("please input...");
        c.startListen();
    }

    public static void main(String[] args) {
        test();
    }

}
